<template>
	<view class="container">
		<!-- 页面头部 -->
		<view class="header">
			<view class="room-title">{{ address }}</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="content-area">
			<!-- 统计卡片区域 -->
			<view class="stats-grid">
				<view class="stat-card" :class="[activeTab === 'locks' ? 'active blue' : 'blue']"
					@click="switchTab('locks')">
					<view class="stat-details"><text class="stat-title">智能锁</text><text
							class="stat-value">1</text></view>
				</view>
				<view class="stat-card" :class="[activeTab === 'users' ? 'active green' : 'green']"
					@click="switchTab('users')">
					<view class="stat-details"><text class="stat-title">人员</text><text
							class="stat-value">{{ usersCount || 0 }}</text></view>
				</view>
				<view class="stat-card" :class="[activeTab === 'keys' ? 'active orange' : 'orange']"
					@click="switchTab('keys')">
					<view class="stat-details"><text class="stat-title">钥匙</text><text
							class="stat-value">{{ keysCount || 0 }}</text></view>
				</view>
				<view class="stat-card" :class="[activeTab === 'logs' ? 'active purple' : 'purple']"
					@click="switchTab('logs')">
					<view class="stat-details"><text class="stat-title">开门记录</text><text
							class="stat-value">{{ openLogsCount || 0 }}</text></view>
				</view>
			
				
			</view>

			<!-- 标签内容区域 -->
			<view class="tab-content">
				<!-- 智能锁内容 -->
				<view v-if="activeTab === 'locks'" class="content-section content-section-animated">
					<smartlocks :roomId="roomId" @generate-password="handleGeneratePassword" />
				</view>

				<!-- 开门记录内容 -->
				<view v-if="activeTab === 'logs'" class="content-section content-section-animated">
					<OpenLogs :roomId="roomId" />
				</view>

				<!-- 住户钥匙内容 -->
				<view v-if="activeTab === 'keys'" class="content-section content-section-animated">
					<TenantKey :roomId="roomId" />
				</view>

				<!-- 住户信息内容 -->
				<view v-if="activeTab === 'users'" class="content-section content-section-animated">
					<TenantUsers :roomId="roomId" @update-users-count="handleUsersCountUpdate" />
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		getHome
	} from '@/api/lock/home';
	import {
		hxAddSingleKey
	} from '@/api/lock/details';
	import {
		getLockListByHomeId
	} from '@/api/lock';
	import {
		listOpenlock
	} from '@/api/lock/openlock';
	import {
		listTenantkey
	} from '@/api/lock/tenantKeys';
	import request from '@/utils/request';
	import smartlocks from './components/smartlocks.vue';
	import OpenLogs from './components/openLogs.vue';
	import TenantKey from './components/tenant-key.vue';
	import TenantUsers from './components/tenantUsers.vue';

	export default {
		components: {
			smartlocks,
			OpenLogs,
			TenantKey,
			TenantUsers,
		},
		data() {
			return {
				roomId: null,
				address: '',
				activeTab: 'locks',
				smartlocksList: [],
				openLogsCount: 0,
				tenantsCount: 0,
				keysCount: 0,
				usersCount: 0,
				usersList: [],
				tempPassword: null,
				currentLock: null,
				passwordValidTime: null
			}
		},
		onLoad(options) {
			console.log('页面加载，options:', options);
			this.roomId = options.id;
			console.log('设置roomId:', this.roomId);
			this.loadData();
		},
		onPullDownRefresh() {
			// 下拉刷新
			Promise.all([
				this.loadData()
			]).then(() => {
				// 刷新成功提示
				uni.showToast({
					title: '刷新成功',
					icon: 'success',
					duration: 1500
				});
			}).catch(error => {
				console.error('刷新数据失败：', error);
				uni.showToast({
					title: '刷新失败',
					icon: 'none'
				});
			}).finally(() => {
				// 停止下拉刷新动画
				uni.stopPullDownRefresh();
			});
		},
		methods: {
			loadData() {
				console.log('开始加载数据，roomId:', this.roomId);
				uni.showLoading({
					title: '加载中...'
				});

				return Promise.all([
					getHome(this.roomId),
					this.getSmartlocksCount(),
					this.getOpenLogsCount(),
					this.getKeysCount(),
					this.getUsersCount() // 添加获取住户数量
				]).then(([homeRes, smartlocksRes, openLogsRes, keysRes, usersRes]) => {
					// 处理房间基本信息
					if (homeRes.code === 200) {
						const data = homeRes.data;
						if (data) {
							this.address = (data.cellName || '') + '/' +
								(data.unitName || '') + '/' +
								(data.floorName || '') + '/' +
								(data.roomName || '');
						}
					} else {
						uni.showToast({
							title: '加载房间信息失败',
							icon: 'none'
						});
					}
					
					// 确保所有计数都已设置
					console.log('数据加载完成:', {
						smartlocks: this.smartlocksList.length,
						openLogs: this.openLogsCount,
						keys: this.keysCount,
						users: this.usersCount
					});
					
					uni.hideLoading();
					return homeRes;
				}).catch(err => {
					console.error('获取数据失败', err);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
					uni.hideLoading();
					return Promise.reject(err);
				});
			},

			// 获取智能锁数量
			getSmartlocksCount() {
				return getLockListByHomeId(this.roomId).then(res => {
					if (res.code === 200) {
						if(res.data){
							this.smartlocksList = [res.data];
						}
					}
					return res;
				});
			},

			// 获取开门记录数量
			getOpenLogsCount() {
				console.log('开始获取开门记录数量，roomId:', this.roomId);
				return listOpenlock({
					pageNum: 1,
					pageSize: 1,
					homeId: this.roomId
				}).then(res => {
					console.log('开门记录API响应:', res);
					if (res.code === 200) {
						this.openLogsCount = res.total || 0;
						console.log('设置开门记录数量:', this.openLogsCount);
					} else {
						console.error('获取开门记录数量失败:', res.msg);
					}
					return res;
				}).catch(err => {
					console.error('获取开门记录数量异常:', err);
					return { code: 500, msg: '获取开门记录数量失败' };
				});
			},

			// 获取住户钥匙数量
			getKeysCount() {
				return listTenantkey({
					pageNum: 1,
					pageSize: 1,
					homeId: this.roomId
				}).then(res => {
					if (res.code === 200) {
						this.keysCount = res.total || 0;
					}
					return res;
				});
			},

			// 获取住户数量
			getUsersCount() {
				return request({
					url: '/tenantuser/tenant/listruzhu',
					method: 'get',
					params: {
						homeId: this.roomId,
						isFlag: 1,
						pageNum: 1,
						pageSize: 1
					}
				}).then(res => {
					if (res.code === 200) {
						this.usersCount = res.total || 0;
					}
					return res;
				});
			},
			switchTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
			},
			refreshData() {
				this.loadData();
				// 刷新图标动画效果
				const refreshBtn = document.querySelector('.refresh-button');
				if (refreshBtn) {
					refreshBtn.classList.add('rotating');
					setTimeout(() => {
						refreshBtn.classList.remove('rotating');
					}, 1000);
				}
			},
			handleGeneratePassword(lock) {
				// 保存当前锁信息
				this.currentLock = lock;
				this.tempPassword = null;
				this.passwordValidTime = null;

				// 显示密码弹窗
				this.$refs.passwordPopup.open();

				// 生成临时密码
				this.generateTempPassword(lock);
			},
			generateTempPassword(lock) {
				if (!lock || !lock.mac) {
					uni.showToast({
						title: '无法获取设备信息',
						icon: 'none'
					});
					return;
				}

				// 构建请求参数
				const params = {
					type: 1, // 临时密码类型
					mac: lock.mac,
					homeId: this.roomId
				};

				// 调用API生成密码
				hxAddSingleKey(params).then(res => {
					if (res.code === 200 && res.data) {
						this.tempPassword = res.data.password || res.data.jieMiPassword;
						this.passwordValidTime = res.data.endTime || '24小时内';
					} else {
						uni.showToast({
							title: res.msg || '生成密码失败',
							icon: 'none'
						});
						this.closePasswordPopup();
					}
				}).catch(err => {
					console.error('生成密码失败', err);
					uni.showToast({
						title: '生成密码失败',
						icon: 'none'
					});
					this.closePasswordPopup();
				});
			},
			closePasswordPopup() {
				this.$refs.passwordPopup.close();
			},
			handleUsersCountUpdate(count) {
				this.usersCount = count;
			}
		}
	}
</script>

<style lang="scss">
	@font-face {
		font-family: "iconfont";
		src: url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAeEAAsAAAAADZQAAAc2AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDMgqOdIx/ATYCJAMUCwwABCAFhGcHgQsbXgxRlFBOGdkX2DbskTohQjRaWjQt0viXAwcAQAQEQPBfWu39mZlFYBOTqJdoFglCJxFC0TQSJZFA6IQSzRL+h36532MuUzZbm/yJrYIVtmjZeqK0V7W1V7rDR0gIRVl25s/u3vuJQtGqqkSJRKbDIB6lKEQqlYnQCZW1nY2zqLsuX0/R/+dY6bOAzX/bzr07AUYBBhjt84LFTcACIkDegjeY3XTO4QQazTMlbF1evwU1hTIuEPcqogA1wx1KoYbq0Jxzs4iXUDXTM/IM8CL8fvzhjqgkNZlx071L8Qa+/NXPzUOuf54BWN/OYVtExhygEB9zfR9kh+YcNJr8uYJjQH+nkvL1c3Ob5v9/isoSqv8yiAZtihp20fyjF6JkKnV0wdaD2a+cOsOvLKf5tXIGv85+RVTRe4ZGRbcZYv/WQeZ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3wbkXiRtKnTW/J2yBq6qlQeQ3eeYacmhYkD5W8BHrF2mB5ovXSXh8qepCGygMXCr4/6bXMrnXMtXa2XRrfU9UmTF1anTdtsdG/MrpSuExYpahSC8xvLljbnnNrIZwC1/a5J1nLZHCZTCyHU45gvQQDHC5Lw+oYKoeiojx9GgUyiusYp9XoOV4jQmHVS40bnYzDYg7GjBZyJzIwu5FRBWKo9FQR1xmNHMV1XpqLU8TkzFe9ZkEGHgT/wUCfXnZp2QpN09KygXOTQtXGK6sGryQMWWkgKRJFKdHLB0eXkbR0dPRy0jK696Jz+4d2gMPF8JT1UlaQJqnTk+yTwwsPL/ZJViWF2YOGnzV48FmtQZSN5t9q4JRyucx1pnGkMU1mnw04pbycB5FzxH+49l9Qka8lksmOUhJUqA0kLd75BfXE1JnLxYLiQRqm1b4GmGr5KshHi6sVQaUFG2CuhUw6pPJyDm8ABo+DGhoGx7RxtExnNMAJ0KHGnbkOnT+YARh7g2HiLBjhFugwdR50mPsN/3dKDxGBqJogHSlCbOwjB4HtKO4Igjo1vOYGnJ2kW7LoGP2OcRsVZpjK+ZeYRqxwNh7kH+QJy3Kej1gzSEbYmC08BBsyCYldMImzGPNIbXYNxOzs1NTYp4Fg7ajiHAQKdMrgas6By90+XVaK5svfMdyMEpqBwOAr/EWYlAiusDTeBPmQ9jYW5eI4qkkgiaBJZ0NYSIJ1YBIgQ0WciGFcKoQ8kqpZS4FoWH0VZ7aq5/2ZrQo+x+2EJEcVdTTRRhe9NGnTMXrvVd/FZPWcPqI+cFgZUVKyPiBm2sVhS/dEqmIcm7BIWi6FxdkVZm7XoeMiGUPIBAAA') format('woff2');
	}

	.iconfont {
		font-family: "iconfont" !important;
		font-size: 24px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		color: #FFFFFF;
	}

	.container {
		padding: 0;
		background-color: #f5f7fa;
		min-height: 100vh;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx;
		background: linear-gradient(135deg, #4B71F7, #3A5FE0);
		box-shadow: 0 4rpx 20rpx rgba(75, 113, 247, 0.3);
		position: relative;

		.room-title {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
			color: #fff;
			text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			padding: 0 20rpx;
		}

		.refresh-button {
			width: 70rpx;
			height: 70rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
			background-color: rgba(255, 255, 255, 0.2);
			transition: all 0.3s ease;

			&.rotating {
				animation: rotate 1s linear infinite;
			}

			&:active {
				background-color: rgba(255, 255, 255, 0.3);
				transform: scale(0.95);
			}

			.iconfont {
				color: #fff;
				font-size: 40rpx;
			}
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.content-area {
		padding: 30rpx 20rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}

	.stats-grid {
		display: flex;
		flex-wrap: nowrap;
		gap: 20rpx;
		width: 100%;
	}

	.stat-card {
		flex: 1;
		padding: 25rpx;
		border-radius: 16rpx;
		color: white;
		width: calc(33.33% - 14rpx);
		display: flex;
		align-items: center;
		transition: all 0.3s ease;
		box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
		position: relative;
		overflow: hidden;

		&::after {
			content: '';
			position: absolute;
			top: -20rpx;
			right: -20rpx;
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
			background: rgba(255, 255, 255, 0.1);
			z-index: 1;
		}

		&::before {
			content: '';
			position: absolute;
			bottom: -30rpx;
			left: -30rpx;
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			background: rgba(0, 0, 0, 0.05);
			z-index: 1;
		}

		&.blue {
			background: linear-gradient(135deg, #1890ff, #096dd9);
		}

		&.purple {
			background: linear-gradient(135deg, #722ed1, #531dab);
		}

		&.green {
			background: linear-gradient(135deg, #52c41a, #389e0d);
		}

		&.orange {
			background: linear-gradient(135deg, #fa8c16, #d46b08);
		}

		&.active {
			transform: translateY(-5rpx);
			box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.15);
		}

		.stat-icon {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: rgba(255, 255, 255, 0.2);
			border-radius: 50%;
			margin-right: 20rpx;
			position: relative;
			z-index: 2;

			.iconfont {
				color: white;
				font-size: 40rpx;
			}
		}

		.stat-details {
			display: flex;
			flex-direction: column;
			position: relative;
			z-index: 2;

			.stat-title {
				font-size: 24rpx;
				opacity: 0.9;
				margin-bottom: 10rpx;
			}

			.stat-value {
				font-size: 40rpx;
				font-weight: bold;
			}
		}
	}

	.tab-content {
		flex: 1;
	}

	.content-section {
		background-color: #FFFFFF;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.08);
		margin-bottom: 20rpx;
	}

	.content-section-animated {
		animation: fadeIn 0.3s ease-in-out;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	// 临时密码弹窗样式
	.password-popup {
		width: 600rpx;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.password-popup-header {
		background: linear-gradient(135deg, #4B71F7, #3A5FE0);
		color: white;
		padding: 25rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.popup-title {
			font-size: 32rpx;
			font-weight: 500;
		}

		.iconfont {
			font-size: 36rpx;
			color: rgba(255, 255, 255, 0.8);
		}
	}

	.password-popup-content {
		padding: 40rpx 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.password-lock-icon {
		width: 120rpx;
		height: 120rpx;
		background: linear-gradient(135deg, #4B71F7, #3A5FE0);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		box-shadow: 0 8rpx 20rpx rgba(75, 113, 247, 0.3);

		.iconfont {
			font-size: 60rpx;
		}
	}

	.password-display {
		width: 100%;

		.password-digits {
			display: flex;
			justify-content: center;
			flex-wrap: nowrap;
			margin-bottom: 30rpx;

			.password-digit {
				width: 70rpx;
				height: 90rpx;
				margin: 0 8rpx;
				background-color: #f5f7fa;
				border-radius: 10rpx;
				font-size: 40rpx;
				font-weight: bold;
				color: #303133;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.08);
			}
		}

		.password-info {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx 30rpx;
			background-color: #f5f7fa;
			border-radius: 10rpx;

			.iconfont {
				color: #4B71F7;
				margin-right: 15rpx;
				font-size: 36rpx;
			}

			text:last-child {
				color: #606266;
				font-size: 26rpx;
				text-align: center;
			}
		}

		.password-loading {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 40rpx 0;

			.iconfont {
				color: #4B71F7;
				font-size: 60rpx;
				margin-bottom: 20rpx;
			}

			text:last-child {
				color: #606266;
				font-size: 28rpx;
			}
		}
	}

	.password-popup-footer {
		padding: 20rpx 30rpx 30rpx;
		display: flex;
		justify-content: center;

		.popup-btn {
			background: linear-gradient(135deg, #4B71F7, #3A5FE0);
			color: white;
			font-size: 32rpx;
			padding: 20rpx 0;
			width: 80%;
			text-align: center;
			border-radius: 50rpx;
			box-shadow: 0 6rpx 15rpx rgba(75, 113, 247, 0.3);
		}
	}

	.spinning {
		animation: rotate 1.5s linear infinite;
	}

	/* 住户信息样式 */
	.users-content {
		padding: 30rpx;
	}

	.users-header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.users-title {
		display: block;
		font-size: 36rpx;
		font-weight: 600;
		color: #303133;
		margin-bottom: 10rpx;
	}

	.users-subtitle {
		display: block;
		font-size: 26rpx;
		color: #909399;
	}

	.users-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.user-item {
		display: flex;
		align-items: center;
		padding: 25rpx;
		background-color: #f8f9fa;
		border-radius: 16rpx;
		border: 2rpx solid rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
	}

	.user-item:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.user-avatar {
		width: 80rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #4B71F7, #3A5FE0);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(75, 113, 247, 0.3);
	}

	.user-avatar .iconfont {
		font-size: 40rpx;
		color: #ffffff;
	}

	.user-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.user-name {
		font-size: 30rpx;
		font-weight: 600;
		color: #303133;
	}

	.user-phone {
		font-size: 24rpx;
		color: #909399;
	}

	.user-status {
		margin-left: 20rpx;
	}

	.status-tag {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
		font-weight: 500;
	}

	.status-tag.active {
		background: linear-gradient(135deg, #67c23a, #5daf34);
		color: #ffffff;
		box-shadow: 0 4rpx 12rpx rgba(103, 194, 58, 0.3);
	}

	.status-tag.inactive {
		background: linear-gradient(135deg, #909399, #606266);
		color: #ffffff;
		box-shadow: 0 4rpx 12rpx rgba(144, 147, 153, 0.3);
	}

	.empty-users {
		text-align: center;
		padding: 80rpx 0;
	}

	.empty-icon {
		width: 120rpx;
		height: 120rpx;
		background: rgba(75, 113, 247, 0.1);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 20rpx;
	}

	.empty-icon .iconfont {
		font-size: 60rpx;
		color: #4B71F7;
	}

	.empty-text {
		font-size: 28rpx;
		color: #909399;
	}
</style>